package com.ITArmy.controller;

import com.ITArmy.beans.Blog;
import com.ITArmy.beans.Serialize;
import com.ITArmy.beans.Shows.Book;
import com.ITArmy.beans.Shows.ReadBlog;
import com.ITArmy.beans.Shows.ReadSerialize;
import com.ITArmy.beans.UploadUtil;
import com.ITArmy.beans.User;
import com.ITArmy.common.ServerResponse;
import com.ITArmy.controller.base.BaseController;
import com.ITArmy.dao.*;
import com.ITArmy.filter.LoginFilter;
import com.ITArmy.service.CommentService;
import com.ITArmy.service.SerializeService;
import com.ITArmy.service.TypeService;
import com.ITArmy.util.CheckPicture;
import com.ITArmy.util.GetUserSession;
import com.ITArmy.util.UploadPicture;
import com.ITArmy.util.pictureChange;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 *
 */
@Api(value = "连载接口层次", tags = "连载接口层次Controller层")
@Controller
@RequestMapping("/serialize")

public class SerializeController extends BaseController {
    @Autowired
    UserMapper userMapper;
    @Autowired
    BlogMapper blogMapper;
    @Autowired
    CommentMapper commentMapper;
    @Autowired
    SerializeMapper serializeMapper;
    @Autowired
    PraiseMapper praiseMapper;
    GetUserSession getUserSession = new GetUserSession();
    private static org.apache.log4j.Logger logger = Logger.getLogger(SerializeController.class);


    @RequestMapping("/findAllSerializeByTitle")
    @ApiOperation(value = "根据标题模糊查询，",
            httpMethod = "POST", response = ServerResponse.class)
    public String findAllSerializeByTitle(String title, Model model) {
        ServerResponse serializeServerResponse = serializeService.findAllSerializeByTitle(title);
        model.addAttribute("serializeListByTitle", serializeServerResponse);
        return "serialize";
    }

    @RequestMapping("/delete")
    @ResponseBody
    @ApiOperation(value = "删除连载信息，",
            httpMethod = "DELETE", response = ServerResponse.class)
    public ServerResponse deleteSerialize(Long id) {
        return serializeService.deleteSerialize(id);
    }

    @RequestMapping("/recommendList")
    @ApiOperation(value = "遍历推荐免费连载",
            httpMethod = "POST", response = ServerResponse.class)
    public String recommendList(Model model, HttpServletRequest request) {
        //将user添加到model里面
        getUserSession.addUserModel(request, model);
        //所有的书（连载）放到model里面
        List<Serialize> serializeList = serializeService.recommendList();
        List books = new ArrayList();
        Collections.reverse(serializeList);
        System.out.println("遍历出来的数据有多少条？" + serializeList.size());
        for (int i = 0; i < serializeList.size(); i++) {
            Serialize serialize = serializeList.get(i);
            books.add(new Book((User) userService.findUserById(serialize.getuId()).getData(), serialize));
            System.out.println(serialize);
        }
        model.addAttribute("freeSerialize", books);
        return "freeSerialize";
    }

//    @RequestMapping("/putawayList")
//    @ApiOperation(value = "遍历上架付费连载",
//            httpMethod = "POST", response = ServerResponse.class)
//    public ServerResponse putawayList(Model model) {
//        List<Serialize> serializes=serializeService.putawayList();
//        model.addAttribute("putawayList",serializes);
//        return "";
//    }

    @RequestMapping("/findRecommendByType")
    @ResponseBody
    @ApiOperation(value = "根据连载类型遍历推荐免费连载",
            httpMethod = "POST", response = ServerResponse.class)
    public ServerResponse findRecommendByType(Integer tid) {
        return serializeService.findRecommendByType(tid);
    }


    @RequestMapping("/deleteSerializeByUser")
    @ApiOperation(value = "用户删除某个连载的所有内容")
    @ResponseBody
    public ServerResponse deleteSerializeByUser(long SerializeId) {
        return serializeService.deleteByUser(SerializeId);
    }

    @RequestMapping("/selectBS")
    @ApiOperation(value = "前台的搜索框进行搜索", httpMethod = "GET")
    public String selectBS(String name, Model model) {
        logger.info("传入的搜索值为:" + name);
        //将侧边栏放入
        ServerResponse typeServerResponse = typeService.typeList();
        List<Blog> blogs = blogMapper.findBlogByTitle(name);
        System.out.println("一共有：" + blogs.size());
        List<Serialize> serializes = serializeMapper.findAllSerializeByTitle(name);
        //进行集合的逆序
        Collections.reverse(blogs);
        Collections.reverse(serializes);
        List<ReadBlog> blogList = new ArrayList();
        List serializeList = new ArrayList();
        for (int i = 0; i < blogs.size(); i++) {
            Blog blog = blogs.get(i);
            ReadBlog readBlog = new ReadBlog();
            readBlog.setBlog(blog);
            readBlog.setUser(userMapper.selectByPrimaryKey(blog.getuId()));
            readBlog.setLikeNumber(praiseMapper.selectBlogPraiseCount(blogs.get(i).getbId()).size());
            readBlog.setCommentNumber(commentMapper.findCommentByBlogId(blogs.get(i).getuId()).size());
            blogList.add(readBlog);
            //进行显示是否点赞过这个博客
            if (praiseMapper.selectPraise(getUserSession.getUser(request).getuId(), blog.getuId()) != null) {
                readBlog.setLike(true);
            } else {
                readBlog.setLike(false);
            }
        }
        for (int i = 0; i < serializes.size(); i++) {
            Serialize serialize = serializes.get(i);
            serializeList.add(new ReadSerialize(userMapper.selectByPrimaryKey(serialize.getuId()), serialize));
        }
        System.out.println("全部都搜索过了...");
        model.addAttribute("allBlogType", typeServerResponse.getData());
        model.addAttribute("serialize", serializeList);
        model.addAttribute("blogs", blogList);
        return "blogType";
    }

    //============================
    @RequestMapping("/uploadCover")
    @ResponseBody
    @ApiOperation(value = "上传封面", httpMethod = "POST")
    public ServerResponse uploadCover(HttpServletRequest request, @ApiParam("封面图片") MultipartFile multiUploadFile, long sId, Model model) throws Exception {
        return serializeService.uploadCoverPicture(request, sId, multiUploadFile);
    }

    //进入写章节的页面,获取所有已经发表过的连载
    //====================
    @RequestMapping("/goChagpterPage")
    @ApiOperation(value = "进入写章节的页面，", httpMethod = "POST", response = String.class)
    public String goChagpterPage(Model model) {
        model.addAttribute("serialize", serializeService.getAllPublicSerialize(request));
        return "Serialization";
    }

    @RequestMapping("/serializePage")
    @ApiOperation(value = "获取所有的连载信息，", httpMethod = "POST", response = String.class)
    public String serializePage(Model model) {
        model.addAttribute("serialize", serializeService.getAllPublicSerialize(request));
        return "bookName";
    }


    @RequestMapping("/writeSerialize")
    @ResponseBody
    @ApiOperation(value = "新建连载", httpMethod = "POST")
    public ServerResponse writeSerialize(Serialize serialize) {
        return serializeService.wirteSerializre(request, serialize);
    }

    //上传测试
    @RequestMapping("/uploadBase")
    @ResponseBody
    @ApiOperation(value = "base64上传图片", httpMethod = "POST")

    public ServerResponse upload(UploadUtil uploadUtil) {
        System.out.println("上传图片...");
        return serializeService.Base64Upload(request, uploadUtil);
    }

    //上传测试
    @RequestMapping("/uploadBodyPicture")
    @ResponseBody
    @ApiOperation(value = "base64上传图片", httpMethod = "POST")
    public ServerResponse uploadBodyPicture(MultipartFile myFileName) {
        System.out.println("我运行了");
        System.out.println("大小为:" + myFileName.getSize());
        UploadPicture uploadPicture = new UploadPicture();
        ServerResponse serverResponse = uploadPicture.upload(myFileName, request, "/static/uploads/serializePicture/");
        if (serverResponse.isSuccess()) {
            System.out.println("上传后的路径为:" + serverResponse.getData());
            return serverResponse;
        }
        System.out.println("上传失败");
        return serverResponse;
    }
}

